var express = require('express');
var app = express();
app.set('view engine', 'jade');
app.use('/static', express.static('static'));

var requestApi = require('./utils/networkUtil');

// error handle
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

app.use(bodyParser());
app.use(methodOverride());
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);

function logErrors(err, req, res, next) {
	console.error(err.stack);
	next(err);
}

function clientErrorHandler(err, req, res, next) {
	if (req.xhr) {
		res.status(500).send({ error: 'Something blew up!' });
	} else {
		next(err);
	}
}

function errorHandler(err, req, res, next) {
	if (res.headersSent) {
		return next(err);
	}
	res.status(500);
	res.render('error', { error: err });
}

// modules import
var birds = require('./controller/birds');
app.use('/birds', birds);

// server start
var server = app.listen(3000, function () {
	var host = server.address().address;
	var port = server.address().port;

	console.log('Example app listening at http://%s:%s', host, port);
});

// root handle
app.all('/', function (req, res, next) {
	console.log(req.originalUrl);
	requestApi.post("/dictionary/query", {"type":"store"}, suc, null);
	next(); // pass control to the next handler
});

function suc(data) {
	// console.log(data);
}


app.get('/', function (req, res, next) {
	// res.send('Hello World!');
	console.log("Accessing two");
	next();
}, function (req, res) {
	res.render('index', { title: 'hello', message: 'Hello there!', 
  		url: "/static/images/1.jpg"});
});